package com.jinxin.platform.cdsmsmgr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdsmsmgr.alisms.AliSms;
import com.jinxin.platform.cdsmsmgr.alisms.SmsFactory;
import com.jinxin.platform.cdsmsmgr.mapper.SmsAkInfoMapper;
import com.jinxin.platform.cdsmsmgr.mapper.SmsBusinessInfoMapper;
import com.jinxin.platform.cdsmsmgr.mapper.SmsTemplateInfoMapper;
import com.jinxin.platform.cdsmsmgr.pojo.domains.SmsAkInfo;
import com.jinxin.platform.cdsmsmgr.pojo.domains.SmsSignInfo;
import com.jinxin.platform.cdsmsmgr.pojo.domains.SmsTemplateInfo;
import com.jinxin.platform.cdsmsmgr.pojo.domains.SysUserVO;
import com.jinxin.platform.cdsmsmgr.pojo.entity.*;
import com.jinxin.platform.cdsmsmgr.pojo.enums.*;
import com.jinxin.platform.cdsmsmgr.pojo.vo.SignInfo;
import com.jinxin.platform.cdsmsmgr.pojo.vo.TemplateVo;
import com.jinxin.platform.cdsmsmgr.rpc.SysUserRpc;
import com.jinxin.platform.cdsmsmgr.service.ISmsTemplateService;
import com.jinxin.platform.cdsmsmgr.utils.DateUtil;
import com.jinxin.platform.cdsmsmgr.utils.IdWorker;
import com.jinxin.platform.cdsmsmgr.utils.TxSmsUtil;
import com.jinxin.platform.cdsmsmgr.utils.Utils;
import com.tencentcloudapi.sms.v20210111.models.DescribeSignListStatus;
import com.tencentcloudapi.sms.v20210111.models.DescribeTemplateListStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-06-29
 * @Author: Lingnan
 **/
@Service
@Slf4j
public class SmsTemplateServiceImpl implements ISmsTemplateService {
    @Autowired
    private SmsTemplateInfoMapper templateInfoMapper;
    @Autowired
    private SysUserRpc sysUserRpc;
    @Autowired
    private SmsAkInfoMapper akInfoMapper;
    @Autowired
    private SmsBusinessInfoMapper businessInfoMapper;
    @Resource
    private IdWorker idWorker;

    @Override
    public List<SmsTemplateInfo> listPage(HashMap param) {
        return templateInfoMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return templateInfoMapper.listPageCount(param);
    }

    @Override
    public ResultEntity saveOrUpdate(SmsTemplateInfo templateInfo) {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        HashMap param = new HashMap();
        String userAccount = currentUser.getUserAccount();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);//admin
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"请先配置accessKeyId和accessSecret","");
        }
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
        String code = templateInfo.getCode();
        if(StringUtils.isEmpty(code)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"模板code不存在","");
        }
        Integer accountType = templateInfo.getAccountType();
        HashMap param2 = new HashMap();
        param2.put("code",code);
        param2.put("accountType",accountType);
        SmsTemplateInfo info = templateInfoMapper.selectOne(param2);
        if(info != null){
            return new ResultEntity(CommonCodeEntity.ALREADY_EXIST,"模板code已存在","");
        }
        int count;
        if(!StringUtils.isEmpty(templateInfo.getId())){
            count = templateInfoMapper.updateByKey(templateInfo);
        }else {
            if(Constant.ACCOUNT_TYPE_TX.equals(accountType)){
                TxSmsTemplateQueryParam smsTemplateQueryParam = new TxSmsTemplateQueryParam();
                smsTemplateQueryParam.setSecretId(akId);
                smsTemplateQueryParam.setSecretKey(akSecret);
                smsTemplateQueryParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
                Long[] templateIdSet = new Long[]{Long.valueOf(code)};
                smsTemplateQueryParam.setTemplateIdSet(templateIdSet);
                JsonResult jsonResult = TxSmsUtil.describeSmsTemplateList(smsTemplateQueryParam);
                if(!jsonResult.getSuccess()){
                    return new ResultEntity(CommonCodeEntity.PARAM_ERR, jsonResult.getMsg(),"");
                }
                DescribeTemplateListStatus [] templateStatusSet =
                        (DescribeTemplateListStatus[]) jsonResult.getData();
                if(templateStatusSet.length > 0){
                    DescribeTemplateListStatus templateStatus = templateStatusSet[0];
                    // 申请模板状态，其中0表示审核通过，1表示审核中，-1表示审核未通过或审核失败。
                    Long statusCode = templateStatus.getStatusCode();
                    int status = 0;
                    if(statusCode == Constant.AUDIT_STATUS_INIT){
                        status = Constant.SMS_STATUS_AUDITING;//0
                    }else if(statusCode == Constant.AUDIT_STATUS_PASS){
                        status = Constant.SMS_STATUS_AUDIED_PASS;//1
                    }else if(statusCode == Constant.AUDIT_STATUS_NOT_PASS){
                        status = Constant.SMS_STATUS_AUDIED_UNPASS;//2
                    }
                    templateInfo.setStatus(status);
                }
            }else {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put(SmsConstant.ACCESS_KEY_ID,akId);
                paramMap.put(SmsConstant.ACCESS_SECERT,akSecret);
                paramMap.put(SmsConstant.TEMPLATE_CODE, code);
                try {
                    JsonResult jsonResult = SmsFactory.aliQuerySmsTemplate(paramMap);
                    if(!jsonResult.getSuccess()){
                        return new ResultEntity(CommonCodeEntity.PARAM_ERR, jsonResult.getMsg(),"");
                    }
                    Template template = (Template) jsonResult.getData();
                    if(template != null && Constant.STRING_OK.equals(template.getCode())){
                        templateInfo.setStatus(template.getTemplateStatus());
                    }else {
                        return new ResultEntity(CommonCodeEntity.PARAM_ERR,"查询模板异常: " + template.getMessage(),"");
                    }
                } catch (ClientException e) {
                    e.printStackTrace();
                    return new ResultEntity(CommonCodeEntity.PARAM_ERR,"查询模板异常: " + e.getMessage(),"");
                }
            }
            templateInfo.setId(Utils.getMillPrimaryKey());
            templateInfo.setCreateTime(LocalDateTime.now());
            templateInfo.setApplyUser(currentUser.getUserAccount());
            templateInfo.setIsDel(Constant.IS_DEL_NO);
            count = templateInfoMapper.insert(templateInfo);
        }
        if(count > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",templateInfo);
        }else {
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败","");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity deleteById(String id) {
        if(StringUtils.isEmpty(id)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"id为空","");
        }
        SmsTemplateInfo templateInfo = templateInfoMapper.selectByKey(id);
        if(templateInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"模板不存在","");
        }
        int count = templateInfoMapper.deleteByKey(id);
        if(count > 0){
            businessInfoMapper.setTemplateNull(id,templateInfo.getAccountType());
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"删除成功","");
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"删除失败","");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity appSmsTemplate(SmsTemplateInfo templateInfo) {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        HashMap param = new HashMap();
        String userAccount = currentUser.getUserAccount();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"请先配置accessKeyId和accessSecret","");
        }
        boolean isApply = StringUtils.isEmpty(templateInfo.getId());
        Integer accountType = templateInfo.getAccountType();
        String name = templateInfo.getName();
        String content = templateInfo.getContent();
        String explain = templateInfo.getExplain();
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
        if(Constant.ACCOUNT_TYPE_ALI.equals(accountType)){
            try {
                AliSms aliSms = new AliSms(akId, akSecret);
                String type = !StringUtils.isEmpty(templateInfo.getType()) ? String.valueOf(templateInfo.getType()) : "";
                CommonResponse response;
                if(isApply){
                    response = aliSms.addSmsTemplate(type, name, content, explain);
                }else {
                    response = aliSms.modifySmsTemplate(type, name, content, explain,templateInfo.getCode());
                }
                ResponseData responseData = JSONObject.parseObject(response.getData(), ResponseData.class);
                if(responseData == null){
                    return new ResultEntity(CommonCodeEntity.FAIL,"调用阿里短信服务失败，请重试","");
                }
                if(!"OK".equals(responseData.getCode())){
                    return new ResultEntity(CommonCodeEntity.FAIL,responseData.getMessage(),"");
                }
                templateInfo.setCode(responseData.getTemplateCode());
            } catch (ClientException e) {
                e.printStackTrace();
                return new ResultEntity(CommonCodeEntity.FAIL,"调用阿里短信服务失败","");
            }
        }else { // 腾讯
            JsonResult jsonResult;
            if(isApply){
                TxAddSmsTemplateParam smsTemplateParam = new TxAddSmsTemplateParam();
                smsTemplateParam.setSecretId(akId);
                smsTemplateParam.setSecretKey(akSecret);
                smsTemplateParam.setTemplateName(name);
                smsTemplateParam.setTemplateContent(content);
                smsTemplateParam.setSmsType(templateInfo.getType());
                smsTemplateParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
                smsTemplateParam.setRemark(templateInfo.getExplain());
                jsonResult = TxSmsUtil.addSmsTemplate(smsTemplateParam);
            }else {
                TxModifySmsTemplateParam templateParam = new TxModifySmsTemplateParam();
                templateParam.setSecretId(akId);
                templateParam.setSecretKey(akSecret);
                templateParam.setTemplateId(Integer.valueOf(templateInfo.getCode()));
                templateParam.setTemplateName(name);
                templateParam.setTemplateContent(content);
                templateParam.setSmsType(templateInfo.getType());
                templateParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
                templateParam.setRemark(templateInfo.getExplain());
                jsonResult = TxSmsUtil.modifySmsTemplate(templateParam);
            }
            if(!jsonResult.getSuccess()){
                return new ResultEntity(CommonCodeEntity.FAIL,jsonResult.getMsg(),"");
            }
            templateInfo.setCode((String) jsonResult.getData());
        }
        int count;
        if(isApply){
            templateInfo.setId(Utils.getMillPrimaryKey());
            templateInfo.setCreateTime(LocalDateTime.now());
            templateInfo.setIsDel(Constant.IS_DEL_NO);
            templateInfo.setStatus(Constant.SMS_STATUS_AUDITING);
            templateInfo.setApplyUser(userAccount);
            count = templateInfoMapper.insert(templateInfo);
        }else {
            count = templateInfoMapper.updateByKey(templateInfo);
        }
        if(count > 0){
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc",templateInfo);
        }else {
            return new ResultEntity(CommonCodeEntity.FAIL,"保存失败","");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity updateStatus() {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        HashMap param = new HashMap();
        String userAccount = currentUser.getUserAccount();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"keyId和keySecret未配置","");
        }
        HashMap param2 = new HashMap();
        param2.put("applyUser", Constant.ACCOUNT_ADMIN);
        int accountType = Constant.TX_ACCOUNT.equals(smsAkInfo.getThirdAccountType()) ?
                Constant.ACCOUNT_TYPE_TX :  Constant.ACCOUNT_TYPE_ALI;
        param2.put("accountType", accountType);
        List<SmsTemplateInfo> list = templateInfoMapper.list(param2);
        int size = list.size();
//        if(size == 0){
//            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"模板不存在","");
//        }
        int addCount = 0, updateCount = 0,deletedCount = 0;
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
//        String[] codeArr = list.stream().map(SmsTemplateInfo::getCode).toArray(String[]::new);
        Map<String, SmsTemplateInfo> templateMap =
                list.stream().collect(Collectors.toMap(SmsTemplateInfo::getCode, template -> template));
        if(Constant.ACCOUNT_TYPE_TX.equals(accountType)){
            int limit = Constant.NUMBER_100;//默认数组长度最大100
            int offset = 0;//偏移量。0开始
            while (true){
                TxSmsTemplateQueryParam templateQueryParam = new TxSmsTemplateQueryParam();
                templateQueryParam.setSecretId(akId);
                templateQueryParam.setSecretKey(akSecret);
                templateQueryParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
                templateQueryParam.setOffset(offset);
                templateQueryParam.setLimit(Constant.NUMBER_100);
                JsonResult jsonResult = TxSmsUtil.describeSmsTemplateList(templateQueryParam);
                if(!jsonResult.getSuccess()){
                    log.error("[腾讯]"+jsonResult.getMsg());
                    continue;
                }
                DescribeTemplateListStatus[] describeTemplateStatusSet = (DescribeTemplateListStatus[]) jsonResult.getData();
                if(describeTemplateStatusSet.length == 0){break;}
                for(DescribeTemplateListStatus templateStatus : describeTemplateStatusSet){
                    Long templateId = templateStatus.getTemplateId();
                    SmsTemplateInfo templateInfo = templateMap.get(templateId + "");
                    String templateName = templateStatus.getTemplateName();
                    String templateContent = templateStatus.getTemplateContent();
                    Long statusCode = templateStatus.getStatusCode();
                    String reviewReply = templateStatus.getReviewReply();
                    int status = 0;
                    if(statusCode == Constant.AUDIT_STATUS_PASS){
                        status = Constant.SMS_STATUS_AUDIED_PASS;
                    }else if(statusCode == Constant.AUDIT_STATUS_INIT){
                        status = Constant.SMS_STATUS_AUDITING;
                    }else if(statusCode == Constant.AUDIT_STATUS_NOT_PASS){
                        status = Constant.SMS_STATUS_AUDIED_UNPASS;
                    }
                    SmsTemplateInfo templateInfoNew = new SmsTemplateInfo();
                    if(templateInfo != null){
                        templateInfoNew.setId(templateInfo.getId());
                        Integer oldStatus = templateInfo.getStatus();
                        if(status != oldStatus &&
                                Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                            SmsTemplateInfo templateNew = new SmsTemplateInfo();
                            templateNew.setId(templateInfo.getId());
                            templateNew.setStatus(status);
                            templateNew.setReason(reviewReply);
                            templateNew.setIsDel(Constant.IS_DEL_NO);
                            updateCount += templateInfoMapper.updateByKey(templateNew);
                        }
                    }else{
                        templateInfoNew.setId(idWorker.nextId()+"");
                        templateInfoNew.setCode(String.valueOf(templateId));
                        //由于获取不到短信类型，暂时都设置为普通短信
                        templateInfoNew.setType(Constant.TX_SMS_TYPE_COMMON);
                        templateInfoNew.setName(templateName);
                        templateInfoNew.setContent(templateContent);
                        templateInfoNew.setStatus(status);
                        templateInfoNew.setCreateTime(LocalDateTime.now());//腾讯返回的时间有误
                        templateInfoNew.setApplyUser(currentUser.getUserAccount());
                        templateInfoNew.setReason(reviewReply);
                        templateInfoNew.setAccountType(Constant.ACCOUNT_TYPE_TX);
                        templateInfoNew.setIsDel(Constant.IS_DEL_NO);
                        addCount += templateInfoMapper.insert(templateInfoNew);
                    }
                }
                offset += limit;
            }
        }else {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put(SmsConstant.ACCESS_KEY_ID, akId);
            paramMap.put(SmsConstant.ACCESS_SECERT, akSecret);
            int pageSize = SmsConstant.PAGE_SIZE;
            paramMap.put(SmsConstant.QUERY_PAGE_SIZE,pageSize);
            try {
                TemplateInfo tempInfo = SmsFactory.aliQuerySmsTemplateList(paramMap);
                if(tempInfo != null && tempInfo.getTotalCount() > 0){
                    String account = currentUser.getUserAccount();
                    int[] ints1 = addOrUpdateTemplate(tempInfo, templateMap, account);
                    addCount += ints1[0];
                    updateCount += ints1[1];
                    int totalCount = tempInfo.getTotalCount().intValue();
                    int page = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
                    for (int i = 2; i < page; i++) {
                        paramMap.put(SmsConstant.QUERY_PAGE_INDEX,i);
                        paramMap.put(SmsConstant.QUERY_PAGE_SIZE,pageSize);
                        TemplateInfo templateInfo2 = SmsFactory.aliQuerySmsTemplateList(paramMap);
                        if(templateInfo2 != null && templateInfo2.getSmsTemplateList().size() > 0){
                            int[] ints2 = addOrUpdateTemplate(templateInfo2,templateMap,account);
                            addCount += ints2[0];
                            updateCount += ints2[1];
                        }
                    }
                }
            } catch (ClientException e) {
                e.printStackTrace();
                return new ResultEntity(CommonCodeEntity.FAIL,"更新短信模板列表失败: " + e.getMessage(),"");
            }
        }
        return new ResultEntity(CommonCodeEntity.SUC_CODE,"成功新增"+addCount+"条模板,更新"+updateCount+"条模板","");
    }

    private int[] addOrUpdateTemplate(TemplateInfo tempInfo,
                                     Map<String, SmsTemplateInfo> templateMap,String userAccount){
        int addCount = 0, updateCount = 0;
        List<TemplateObj> templateList = tempInfo.getSmsTemplateList();
        for(TemplateObj templateObj : templateList){
            SmsTemplateInfo templateInfoNew = new SmsTemplateInfo();
            String templateCode = templateObj.getTemplateCode();
            String auditStatus = templateObj.getAuditStatus();
            AliAuditReason auditReason = templateObj.getReason();
            String reason = auditReason != null ? auditReason.getRejectInfo() : "";
            SmsTemplateInfo templateInfo = templateMap.get(templateCode);
            int status = 0;
            switch (auditStatus){
                case Constant.AUDIT_STATE_INIT:
                    status = Constant.SMS_STATUS_AUDITING;break;
                case Constant.AUDIT_STATE_PASS:
                    status = Constant.SMS_STATUS_AUDIED_PASS;break;
                case Constant.AUDIT_STATE_NOT_PASS:
                    status = Constant.SMS_STATUS_AUDIED_UNPASS;break;
                case Constant.AUDIT_STATE_CANCEL:
                    status = Constant.SMS_STATUS_AUDIED_CANCEL;break;
            }
            if(templateInfo != null){
                Integer oldStatus = templateInfo.getStatus();
                if(status != oldStatus &&
                        Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                    SmsTemplateInfo templateNew = new SmsTemplateInfo();
                    templateNew.setId(templateInfo.getId());
                    templateNew.setStatus(status);
                    templateNew.setReason(reason);
                    templateNew.setIsDel(Constant.IS_DEL_NO);
                    updateCount += templateInfoMapper.updateByKey(templateNew);
                }
            }else {
                templateInfoNew.setId(idWorker.nextId()+"");
                templateInfoNew.setCode(templateCode);
                templateInfoNew.setType(templateObj.getOuterTemplateType());
                templateInfoNew.setName(templateObj.getTemplateName());
                templateInfoNew.setContent(templateObj.getTemplateContent());
                templateInfoNew.setStatus(status);
                templateInfoNew.setCreateTime(DateUtil.timeString2LocalDateTime(templateObj.getCreateDate(),null));
                templateInfoNew.setApplyUser(userAccount);
                templateInfoNew.setReason(reason);
                templateInfoNew.setAccountType(Constant.ACCOUNT_TYPE_ALI);
                templateInfoNew.setIsDel(Constant.IS_DEL_NO);
                addCount += templateInfoMapper.insert(templateInfoNew);
            }
        }
        return new int[]{addCount,updateCount};
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultEntity deleteByCode(String code, String id) {
        if(StringUtils.isEmpty(code) || StringUtils.isEmpty(id)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"id或模板code为空","");
        }
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return new ResultEntity(CommonCodeEntity.NO_LOGIN,"未登录用户","");
        }
        HashMap param = new HashMap();
        String userAccount = currentUser.getUserAccount();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        AliSms aliSms = new AliSms(smsAkInfo.getAkId(), smsAkInfo.getAkSecret());
        SmsTemplateInfo templateInfo = templateInfoMapper.selectByKey(id);
        if(templateInfo == null){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"模板不存在","");
        }
        if(!Constant.SMS_STATUS_AUDITING.equals(templateInfo.getStatus())){
            try {
                CommonResponse response = aliSms.deleteSmsTemplate(code);
                Template template = JSONObject.parseObject(response.getData(), Template.class);
                if(template != null && "OK".equals(template.getCode())){
                    int count = templateInfoMapper.deleteByKey(id);
                    if(count > 0){
                        return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","");
                    }
                    return new ResultEntity(CommonCodeEntity.FAIL,template.getMessage()+",删除失败",null);
                }
            } catch (ClientException e) {
                e.printStackTrace();
                return new ResultEntity(CommonCodeEntity.FAIL,"删除模板失败,请重试","");
            }
        }else {
            int count = templateInfoMapper.deleteByKey(id);
            if(count > 0){
                return new ResultEntity(CommonCodeEntity.SUC_CODE,"suc","");
            }
        }
        return new ResultEntity(CommonCodeEntity.FAIL,"删除失败","");
    }

    @Override
    public SmsTemplateInfo getById(String id) {
        return templateInfoMapper.selectByKey(id);
    }

    @Override
    public JsonResult querySmsTemplateList() {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return JsonResult.error("未登录");
        }
        HashMap param = new HashMap();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return JsonResult.error("秘钥对未配置");
        }
        String thirdAccountType = smsAkInfo.getThirdAccountType();
        List<TemplateVo> templateInfoList = new ArrayList<>();
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
        if(Constant.TX_ACCOUNT.equals(thirdAccountType)){
            List<TemplateVo> templateList = new ArrayList<>();
            int offset = 0;
            while (true){
                int count = setTxTemplate(templateList, akId, akSecret, offset);
                if(count == 0){break;}
                offset += Constant.NUMBER_100;
            }
            param.put("accountType",Constant.ACCOUNT_TYPE_TX);
            param.put("idDel",Constant.IS_DEL_NO);//未删除的
            extractTemplateList(param, templateInfoList, templateList);
//            Long[] templateIdSet = list.stream().map(template -> Long.parseLong(template.getCode()))
//                    .toArray(Long[]::new);
        }else {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put(SmsConstant.ACCESS_KEY_ID, akId);
            paramMap.put(SmsConstant.ACCESS_SECERT, akSecret);
            int pageSize = SmsConstant.PAGE_SIZE;
            paramMap.put(SmsConstant.QUERY_PAGE_SIZE,pageSize);
            try {
                TemplateInfo templateInfo = SmsFactory.aliQuerySmsTemplateList(paramMap);
                if(templateInfo != null && templateInfo.getTotalCount() > 0){
                    List<TemplateVo> templateList = new ArrayList<>();
                    setTemplateList(templateList, templateInfo);
                    int totalCount = templateInfo.getTotalCount().intValue();
                    int page = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
                    for (int i = 2; i < page; i++) {
                        paramMap.put(SmsConstant.QUERY_PAGE_INDEX,i);
                        paramMap.put(SmsConstant.QUERY_PAGE_SIZE,pageSize);
                        TemplateInfo templateInfo2 = SmsFactory.aliQuerySmsTemplateList(paramMap);
                        if(templateInfo2 != null && templateInfo2.getSmsTemplateList().size() > 0){
                            setTemplateList(templateList, templateInfo2);
                        }
                    }
                    // 去除本地库已有的数据
                    param.put("accountType",Constant.ACCOUNT_TYPE_ALI);
                    param.put("idDel",Constant.IS_DEL_NO);//未删除的
                    extractTemplateList(param, templateInfoList, templateList);
                }
            } catch (ClientException e) {
                e.printStackTrace();
                return JsonResult.error("查询短信模板列表失败");
            }
        }
        return JsonResult.ok("success",templateInfoList);
    }

    private void extractTemplateList(HashMap param, List<TemplateVo> templateInfoList, List<TemplateVo> templateList) {
        List<SmsTemplateInfo> list = templateInfoMapper.list(param);
        Set<String> codeSet = list.stream().map(SmsTemplateInfo::getCode).collect(Collectors.toSet());
        for(TemplateVo templateVo : templateList){
            if(!codeSet.contains(templateVo.getTemplateId())){
                templateInfoList.add(templateVo);
            }
        }
    }

    private int setTxTemplate(List<TemplateVo> templateInfoList, String akId, String akSecret,int offset) {
        TxSmsTemplateQueryParam templateQueryParam = new TxSmsTemplateQueryParam();
        templateQueryParam.setSecretId(akId);
        templateQueryParam.setSecretKey(akSecret);
        templateQueryParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
        templateQueryParam.setOffset(offset);
        templateQueryParam.setLimit(Constant.NUMBER_100);
        JsonResult jsonResult = TxSmsUtil.describeSmsTemplateList(templateQueryParam);
        if(jsonResult.getSuccess()){
            DescribeTemplateListStatus[] describeTemplateStatusSet = (DescribeTemplateListStatus[]) jsonResult.getData();
            for(DescribeTemplateListStatus status : describeTemplateStatusSet){
                TemplateVo templateVo = new TemplateVo();
                templateVo.setStatus(TemplateAuditStatusEnum.getDesc(status.getStatusCode()));
                String templateContent = status.getTemplateContent();
                templateVo.setTemplateContent(templateContent);
                templateVo.setTemplateName(status.getTemplateName());
                // 模板类型是验证码还是通知判断不了,腾讯的默认就是普通短信
//                String type = Utils.isVerfifyCodeTemplate(templateContent) ?
//                        Constant.TYPE_SMS_VERFIY : Constant.TYPE_SMS_NOTICE;
                templateVo.setType(Constant.TYPE_SMS_COMMON);
                templateVo.setTemplateId(status.getTemplateId()+"");
                templateVo.setApplyTime(DateUtil.getTimeStrBySeconds(status.getCreateTime()));
                templateVo.setReason(status.getReviewReply());
                templateInfoList.add(templateVo);
            }
            return describeTemplateStatusSet.length;
        }
        return 0;
    }

    private void setTemplateList(List<TemplateVo> signInfoList, TemplateInfo aliSign) {
        List<TemplateObj> templateList = aliSign.getSmsTemplateList();
        for(TemplateObj templateObj : templateList){
            TemplateVo templateInfo = new TemplateVo();
            templateInfo.setTemplateId(templateObj.getTemplateCode());
            templateInfo.setType(OuterTemplateType.getDesc(templateObj.getOuterTemplateType()));
            templateInfo.setTemplateName(templateObj.getTemplateName());
            templateInfo.setTemplateContent(templateObj.getTemplateContent());
            String auditStatus = templateObj.getAuditStatus();
            String statusDesc = AuditStatusEnum.getDesc(auditStatus);
            templateInfo.setStatus(statusDesc);
            if(Constant.AUDIT_STATE_NOT_PASS.equals(auditStatus)){
                AliAuditReason reason = templateObj.getReason();
                templateInfo.setReason(statusDesc+","+reason.getRejectInfo());
            }
            templateInfo.setApplyTime(templateObj.getCreateDate());
            signInfoList.add(templateInfo);
        }
    }

    @Override
    public JsonResult freshStatus(String id) {
        SmsTemplateInfo templateInfo = templateInfoMapper.selectByKey(id);
        if(templateInfo == null){
            return JsonResult.error("短信模板不存在");
        }
        HashMap param = new HashMap();
        param.put("userAccount", Constant.ACCOUNT_ADMIN);
        SmsAkInfo smsAkInfo = akInfoMapper.selectOne(param);
        if(smsAkInfo == null){
            return JsonResult.error("秘钥对未配置");
        }
        String akId = smsAkInfo.getAkId();
        String akSecret = smsAkInfo.getAkSecret();
        Integer accountType = templateInfo.getAccountType();
        Integer oldStatus = templateInfo.getStatus();
        String code = templateInfo.getCode();
        if(Constant.ACCOUNT_TYPE_ALI.equals(accountType)){
            try {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put(SmsConstant.ACCESS_KEY_ID,akId);
                paramMap.put(SmsConstant.ACCESS_SECERT,akSecret);
                paramMap.put(SmsConstant.TEMPLATE_CODE, code);
                JsonResult jsonResult = SmsFactory.aliQuerySmsTemplate(paramMap);
                if(!jsonResult.getSuccess()){
                    return jsonResult;
                }
                Template template = (Template) jsonResult.getData();
                if(template != null && Constant.STRING_OK.equals(template.getCode())){
                    Integer status = template.getTemplateStatus();
                    // 数据库签名是审核中与阿里平台的对比
                    if(status != null && !status.equals(oldStatus) && Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                        SmsTemplateInfo templateNew = new SmsTemplateInfo();
                        templateNew.setId(templateInfo.getId());
                        templateNew.setStatus(status);
                        templateNew.setReason(template.getReason());
                        templateInfoMapper.updateByKey(templateNew);
                    }
                    return JsonResult.ok("刷新审核状态成功",null);
                }else {
                    return JsonResult.error(template.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.error("刷新审核状态失败: " + e.getMessage());
            }
        }else {
            TxSmsTemplateQueryParam smsTemplateQueryParam = new TxSmsTemplateQueryParam();
            smsTemplateQueryParam.setSecretId(akId);
            smsTemplateQueryParam.setSecretKey(akSecret);
            smsTemplateQueryParam.setInternational(Constant.SMS_TYPE_DOMESTIC);
            Long[] templateIdSet = new Long[]{Long.valueOf(code)};
            smsTemplateQueryParam.setTemplateIdSet(templateIdSet);
            JsonResult jsonResult = TxSmsUtil.describeSmsTemplateList(smsTemplateQueryParam);
            if(jsonResult.getSuccess()){
                DescribeTemplateListStatus [] templateStatusSet =
                        (DescribeTemplateListStatus[]) jsonResult.getData();
                if(templateStatusSet.length > 0){
                    DescribeTemplateListStatus templateStatus = templateStatusSet[0];
                    // 申请模板状态，其中0表示审核通过，1表示审核中，-1表示审核未通过或审核失败。
                    Long statusCode = templateStatus.getStatusCode();
                    int status = 0;
                    if(statusCode == Constant.AUDIT_STATUS_INIT){
                        status = Constant.SMS_STATUS_AUDITING;//0
                    }else if(statusCode == Constant.AUDIT_STATUS_PASS){
                        status = Constant.SMS_STATUS_AUDIED_PASS;//1
                    }else if(statusCode == Constant.AUDIT_STATUS_NOT_PASS){
                        status = Constant.SMS_STATUS_AUDIED_UNPASS;//2
                    }
                    if(status != oldStatus && Constant.SMS_STATUS_AUDITING.equals(oldStatus)){
                        SmsTemplateInfo smsTemplateInfoNew = new SmsTemplateInfo();
                        smsTemplateInfoNew.setId(id);
                        smsTemplateInfoNew.setStatus(status);
                        smsTemplateInfoNew.setReason(templateStatus.getReviewReply());
                        templateInfoMapper.updateByKey(smsTemplateInfoNew);
                    }
                }
                return JsonResult.ok("刷新审核状态成功",null);
            }
            return jsonResult;
        }
    }

    @Override
    public JsonResult syncSmsTemp(List<TemplateVo> templateInfoList) {
        SysUserVO currentUser = sysUserRpc.getCurrentUser();
        if(currentUser == null) {
            return JsonResult.error("未登录");
        }
        int count = 0;
        for(TemplateVo templateVo : templateInfoList){
            SmsTemplateInfo templateInfo = new SmsTemplateInfo();
            templateInfo.setId(Utils.getMillPrimaryKey());
            templateInfo.setCode(templateVo.getTemplateId());
            Integer accountType = templateVo.getAccountType();
            // 阿里0验证码1短信通知2推广短信,腾讯0普通短信1营销短信
            String statusDesc = templateVo.getStatus();
            Long code;
            if(Constant.ACCOUNT_TYPE_TX.equals(accountType)){// 腾讯的也不知道是普通还是营销短信,默认定为普通短信
                templateInfo.setType(Constant.TX_SMS_TYPE_COMMON);
                code = TemplateStatusEnum.getCode(statusDesc);
            }else{
                templateInfo.setType(OuterTemplateType.getCode(templateVo.getType()));
                code = TemplateStatusAliEnum.getCode(statusDesc);
            }
            if(code != null){
                templateInfo.setStatus(code.intValue());
            }
            templateInfo.setName(templateVo.getTemplateName());
            templateInfo.setContent(templateVo.getTemplateContent());
            templateInfo.setCreateTime(DateUtil.timeString2LocalDateTime(templateVo.getApplyTime(),null));
            templateInfo.setApplyUser(currentUser.getUserAccount());
            templateInfo.setReason(templateVo.getReason());
            templateInfo.setAccountType(accountType);
            templateInfo.setIsDel(Constant.IS_DEL_NO);
            count += templateInfoMapper.insert(templateInfo);
        }
        return JsonResult.ok("成功同步"+count+"条模板",null);
    }
}
